<!-- 搜索页面组件 -->
<template>
  <div class="m-hmsrch">
    <van-search v-model="keywords" autofocus background="#fbfcfd" clear-trigger="focus" @search="record" @input="fit"
      @focus="fit" shape="round" placeholder="搜索歌曲、歌手、专辑" />
    <div v-show="!issueless">
      <div v-show="!keywords" class="m-default">
        <!-- 热门搜索 -->
        <section class="m-hotlist">
          <h3 class="title">热门搜索</h3>
          <ul class="list">
            <li class="item f-bd f-bd-full" v-for="(item, index) in hotArr" :key="index">
              <span class="link" @click="record(item.first)">{{ item.first }}</span>
            </li>
          </ul>
        </section>
        <!-- 搜索记录 -->
        <section class="m-history">
          <van-cell :title="i" icon="clock-o" v-for="(i, index) in searecHistory" :key="index"
            @click="delline($event, i)" clickable>
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #right-icon>
              <van-icon name="cross" class="search-icon" />
            </template>
          </van-cell>
        </section>
      </div>
      <!-- 查询显示相关歌曲 -->
      <section v-show="keywords && !isFit" class="m-recom">
        <h3 class="title f-bd f-bd-btm f-thide" @click="record(keywords)">搜索“{{ keywords }}”</h3>
        <!-- 搜索中显示 -->
        <van-empty image="network" description="搜索中" v-show="descrip" />
        <!-- 搜索内容相关显示 -->
        <ul v-show="!descrip">
          <li class="recomitem" v-for="(items, index) in suggeation" :key="index" @click="record(items.keyword)">
            <i class="u-svg u-svg-search"></i>
            <span class="f-bd f-bd-btm f-thide">{{ items.keyword }}</span>
          </li>
        </ul>
      </section>
      <!-- 最佳匹配显示 -->
      <div v-show="keywords && isFit" class="m-searchresult">
        <section class="m-matchlist">
          <h3 class="title">最佳匹配</h3>
          <ul>
            <!-- 歌手 -->
            <li class="matchitem album" v-if="multimatch.artist"
              @click="$router.push(`/singerdetails?id=${multimatch.artist[0].id}`)">
              <album-view :album="multimatch.artist" :type="0" :values="keywords"></album-view>
            </li>
            <!-- 专辑 -->
            <li class="matchitem artist" v-if="multimatch.album"
              @click="$router.push(`/albumart?id=${multimatch.album[0].id}`)">
              <album-view :album="multimatch.album" :type="1" :values="keywords"></album-view>
            </li>
            <!-- 歌单 -->
            <li class="matchitem artist" v-if="multimatch.playlist"
              @click="$router.push(`/songlist?id=${multimatch.playlist[0].id}`)">
              <album-view :album="multimatch.playlist" :type="2" :values="keywords"></album-view>
            </li>
          </ul>
        </section>
        <section>
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadMore">
            <search-songs-list :songslist="songsList" :values="keywords"></search-songs-list>
          </van-list>
        </section>
      </div>
    </div>
    <!-- 搜索结果为空 -->
    <div v-show="issueless" class="m-searchresult">
      <div class="m-noresult">暂无搜索结果</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted } from 'vue'
import { hotSearchAPI, multimatchAPI, searchResultListAPI, suggeationsAPI } from '@/api'
import AlbumView from './AlbumView.vue'
import SearchSongsList from './SearchSongsList.vue'

let keywords = ref('') // 搜索内容
let hotArr = ref([]) // 热搜推荐
let searecHistory = ref([]) // 搜索记录
let isFit = ref(false) // 最佳匹配显示与隐藏
let songsList = ref([]) // 搜索结果的歌曲列表
let suggeation = ref([]) // 搜索建议
let multimatch = ref([]) // 多重匹配
let descrip = ref(false) // 加载中状态显示
let issueless = ref(false) // 没有结果显示
let loading = ref(false) // 搜索结果加载状态
let finished = ref(false) // 搜索结果触底状态
let offset = ref(0) // 数据偏移量

onBeforeMount(() => {
  hotSearchAPI().then((res) => {
    hotArr.value = res.data.result.hots
  })
})

onMounted(() => {
  searec()
})

// 本地储存地址
function searec() {
  if (!localStorage.getItem('searecList')) {
    localStorage.getItem('searecList', '[]')
  } else {
    searecHistory.value = JSON.parse(localStorage.getItem('searecList'))
  }
}
function suggeations() {
  suggeationsAPI(keywords.value).then((res) => {
    suggeation.value = res.data.result.allMatch
  })
}
// 回车记录搜索内容
function record(val) {
  // 去除文字的空格
  val = val.replace(/\s/g, '')
  // 空字符串不执行搜索方法
  if (!val) {
    issueless.value = true
    return
  } else {
    issueless.value = false
  }
  // 显示最佳匹配
  isFit.value = true
  // 搜索结果
  offset.value = 0
  searchResultListAPI({ keywords: val, offset: 0 }).then((res) => {
    songsList.value = res.data.result.songs
  })
  // 搜索多重匹配
  multimatchAPI({ keywords: val }).then((res) => {
    multimatch.value = res.data.result
  })
  // 记录搜索内容
  keywords.value = val
  searecHistory.value.unshift(val || keywords.value)
  let historyArr = new Set(searecHistory.value)
  localStorage.setItem('searecList', JSON.stringify(Array.from(historyArr)))
  searec()
}
// 点击删除记录事件
function delline(e, i) {
  if (e.target.className == 'search-icon van-icon van-icon-cross') {
    let fil = searecHistory.value.filter(function (item) {
      return item != e.path[1].innerText
    })
    searecHistory.value = fil
    localStorage.setItem('searecList', JSON.stringify(fil))
    searecHistory.value = JSON.parse(localStorage.getItem('searecList'))
  } else {
    // 点击记录实现搜索/置顶
    keywords.value = i
    isFit.value = true
    record(i)
  }
}
// 输入框变化
function fit() {
  isFit.value = false
  issueless = false
  if (!keywords.value.replace(/\s/g, '')) {
    descrip.value = true
  } else {
    descrip.value = false
    suggeations()
  }
}
// 触底加载
function loadMore() {
  offset.value += 30
  loading.value = true
  let data = {
    keywords: keywords.value,
    offset: offset.value,
  }
  // 发送http请求,获取当前类别下的下一页数据,更新列表
  searchResultListAPI(data).then((res) => {
    if (offset.value >= res.data.result.songCount) {
      // 数据全部加载完成
      finished.value = true
    } else {
      songsList.value = [...songsList.value, ...res.data.result.songs]
      // 加载状态结束
      loading.value = false
    }
  })
}
</script>

<style lang="scss" scoped>
.m-hmsrch {
  background: #fbfcfd;
  border-top: 1px solid #ccc;

  :deep(.van-search) {
    .van-search__content {
      background-color: #ebecec;
    }
  }

  .m-default {
    border-top: 1px solid rgba(0, 0, 0, 0.1);

    .m-hotlist {
      padding: 15px 10px 0;

      .title {
        font-size: 12px;
        line-height: 12px;
        color: #666;
        font-weight: 400;
        margin: 0;
      }

      .list {
        margin: 10px 0 7px;
        position: relative;

        &>li {
          list-style: none;
        }

        .link {
          color: #333;
        }

        .f-bd:after {
          width: 200%;
          height: 200%;
          transform: scale(0.5);
          position: absolute;
          z-index: 2;
          content: '';
          top: 0;
          left: 0;
          pointer-events: none;
          box-sizing: border-box;
          transform-origin: top left;
          border: 0 solid rgba(0, 0, 0, 0.1);
        }

        .item {
          display: inline-block;
          height: 32px;
          margin: 0 8px 8px 0;
          padding: 0 14px;
          font-size: 14px;
          line-height: 32px;
          border: 1px solid #d3d4da;
          border-radius: 32px;
        }
      }
    }
  }

  .m-recom {
    margin: 0 auto;
    border-top: 1px solid rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0;
    }

    .title {
      height: 50px;
      margin-left: 10px;
      padding-right: 10px;
      font-size: 15px;
      line-height: 50px;
      color: #507daf;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }

    .recomitem {
      display: flex;
      align-items: center;
      height: 45px;
      padding-left: 10px;
    }

    i {
      flex: 0 0 auto;
      margin-right: 7px;
    }

    span {
      display: inline-block;
      flex: 1;
      width: 1%;
      padding-right: 10px;
      font-size: 15px;
      line-height: 45px;
      color: #333;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }

    span:after {
      border-color: rgba(0, 0, 0, 0.1);
    }
  }
}

.m-searchresult {
  background: #fcfcfd;
}

.m-noresult {
  padding: 20px 0;
  text-align: center;
}

.f-bd {
  position: relative;
}

.f-thide {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: normal;
}

.u-svg-search {
  width: 15px;
  height: 15px;
  background-image: url('../assets/img/search.svg');
}

.u-svg {
  display: inline-block;
  vertical-align: middle;
  background-position: 0 0;
  background-size: contain;
  background-repeat: no-repeat;
}

.m-searchresult {
  background: #fcfcfd;
  border-top: 1px solid rgba(0, 0, 0, 0.1);

  .m-matchlist {
    padding: 8px 0 4px;

    h3 {
      margin: 0;
    }

    .title {
      margin-left: 10px;
      font-size: 12px;
      line-height: 16px;
      color: #666;
    }

    .matchitem {
      position: relative;
      height: 66px;
    }
  }
}
</style>
